package com.gzhu.knowledgeAdmin.service.impl;

import com.gzhu.knowledgeAdmin.common.exception.BusinessException;
import com.gzhu.knowledgeAdmin.common.exception.GuliException;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.service.OssService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author laoba
 * @create 2023-04-28 18:19
 */
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String upload(MultipartFile file) throws IOException {

        // 获取文件原本的名字
        String originName = file.getOriginalFilename();
        // 取出文件的后缀
        int count = 0;
        for (int i = 0; i < originName.length(); i++) {
            if (originName.charAt(i) == '.') {
                count = i;
                break;
            }
        }
        String fileType = originName.substring(count + 1); //文件类型
        // 验证类型
        if(!fileType.equals("jpg")&&!fileType.equals("png")){
            throw new GuliException(433,"只能是jpg或者png的文件");
        }

        // 创建保存路径
        //日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String format = sdf.format(new Date());
        String savePath = "http://localhost:9000/image/" +format;

        // 保存文件的文件夹
        File folder = new File(getClass().getClassLoader().getResource("").getPath() + "static/image/"+format);
        if(!folder.exists()){
           folder.mkdirs();
        }

        // 设置保存名字
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String saveName = uuid+originName;

        file.transferTo(new File(folder, saveName));
        String url = savePath + "/" + saveName;

        return url;
    }

    @Override
    public void deleleFile(String url) throws MalformedURLException {


        URL newUrl = new URL(url);
        String path = newUrl.getFile();
        // 获取文件路径
        String filePath = getClass().getClassLoader().getResource("").getPath()+"static"+path;

        File file = new File(filePath);

        if (file.exists()) {
            if (file.delete()) {
                return;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        } else {
            throw new BusinessException(ErrorCode.FILE_NOT_FOUND_ERROR);
        }
    }
}
